package com.lglin.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.lglin.bean.user.entity.Address;
import com.lglin.bean.user.entity.SelfUserDetail;
import com.lglin.bean.user.entity.User;
import com.lglin.bean.user.vo.UserInfoVo;
import com.lglin.common.bean.Review;
import com.lglin.common.utils.bean.BeanCopyUtil;
import com.lglin.common.utils.other.CommonUtil;
import com.lglin.common.utils.reponse.ResultBean;
import com.lglin.common.utils.reponse.ResultEnum;
import com.lglin.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.util.*;


@RestController
@RequestMapping("user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 进行用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("register")
    public ResultBean register(@Validated @RequestBody User user) {
        if (userService.checkNickname(user.getNickname()) && userService.checkEmail(user.getEmail())) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encodePassword = bCryptPasswordEncoder.encode(user.getPassword());
            user.setPassword(encodePassword);
            boolean result = userService.register(user);
            if (result) {
                return ResultBean.success().setResultEnum(ResultEnum.Register_Success);
            }
        }
        return ResultBean.fail().setResultEnum(ResultEnum.Register_Fail);
    }

    /**
     * 检查用户的邮箱和昵称是否可用
     *
     * @param user
     * @return
     */
    @PostMapping("check")
    public ResultBean check(@RequestBody User user) {
        if (user.getNickname() != null) {
            boolean result = userService.checkNickname(user.getNickname());
            if (result) {
                return ResultBean.success().setResultEnum(ResultEnum.Nickname_Enable);
            } else {
                return ResultBean.fail().setResultEnum(ResultEnum.Nickname_Disable);
            }
        } else {
            boolean result = userService.checkEmail(user.getEmail());
            if (result) {
                return ResultBean.success().setResultEnum(ResultEnum.Email_Enable);
            } else {
                return ResultBean.fail().setResultEnum(ResultEnum.Email_Disable);
            }
        }
    }

    @GetMapping("userInfo")
    public ResultBean userInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SelfUserDetail userDetail = (SelfUserDetail) authentication.getPrincipal();
        User user = userService.selectById(userDetail.getId());
        if (user != null) {
            return buildUserInfoVo(user);
        }
        return ResultBean.fail().setResultEnum(ResultEnum.Not_Data);
    }

    public ResultBean buildUserInfoVo(User user) {
        UserInfoVo infoVo = BeanCopyUtil.copy(user, UserInfoVo.class);
        List<Integer> userAddressIds = userService.selectUserAddressIdByUId(user.getId());
        if (userAddressIds.isEmpty()) {
            infoVo.setAddresses(null);
        } else {
            List<Address> addresses = userService.selectAddressesById(userAddressIds);
            infoVo.setAddresses(addresses);
        }
        List<Map<String, Object>> userOrder = userService.userOrder(user.getId());
        if (userOrder.size() != 0)
            infoVo.setOrder(userOrder);
        else
            infoVo.setOrder(null);
        return ResultBean.success().data(infoVo).msg("获取用户信息成功");
    }

    @PostMapping("saveInfo")
    public ResultBean saveInfo(@RequestParam("file") MultipartFile file, @RequestParam("nickname") @NotBlank(message = "昵称不能为空") String nickname) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SelfUserDetail userDetail = (SelfUserDetail) authentication.getPrincipal();
        User user = userService.selectById(userDetail.getId());
        if (nickname.equals(user.getNickname())) {
            boolean updateResult = userService.updateUserInfo(userDetail.getId(), file, nickname, userDetail.getUsername());
            if (updateResult) {
                return ResultBean.success().msg("更新信息成功!");
            }
        } else {
            boolean result = userService.checkNickname(user.getNickname());
            if (!result) {
                return ResultBean.fail().setResultEnum(ResultEnum.Nickname_Disable);
            }
        }
        return ResultBean.fail().msg("更新信息失败!");
    }

    @PostMapping("review")
    public ResultBean review(@RequestBody Review review) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SelfUserDetail userDetail = (SelfUserDetail) authentication.getPrincipal();
        review.setUid(userDetail.getId());
        review.setTime(new Date());
        boolean result = userService.insertReview(review);
        if (result) {
            return ResultBean.success().msg("评论成功!");
        }
        return ResultBean.fail().msg("评论失败!");
    }

    @PostMapping("address")
    public ResultBean address(@RequestBody Address address) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SelfUserDetail userDetail = (SelfUserDetail) authentication.getPrincipal();
        if (address.getId() == 0) {
            List<Integer> userAddressIds = userService.selectUserAddressIdByUId(userDetail.getId());
            if (userAddressIds.size() >= 3) {
                return ResultBean.fail().msg("最多只能添加三个默认地址");
            }
            boolean result = userService.insertAddress(address, userDetail.getId());
            if (result) {
                return ResultBean.success().msg("新增地址成功");
            } else {
                return ResultBean.fail().msg("新增地址失败");
            }
        }
        if (address.getId() == -1 && address.getProvince().matches("get")) {
            List<Integer> userAddressIds = userService.selectUserAddressIdByUId(userDetail.getId());
            if (userAddressIds.isEmpty()) {
                return ResultBean.fail().setResultEnum(ResultEnum.Not_Data);
            } else {
                List<Address> addresses = userService.selectAddressesById(userAddressIds);
                return ResultBean.success().data(addresses);
            }
        }
        if (address.getProvince().equals("delete")) {
            boolean result = userService.deleteAddressById(address.getId());
            if (result) {
                return ResultBean.success().msg("删除成功");
            } else {
                return ResultBean.fail().msg("删除失败");
            }
        }
        boolean result = userService.updateAddressById(address);
        if (result) {
            return ResultBean.success().msg("更新成功");
        }
        return ResultBean.fail().msg("更新失败");
    }

    @GetMapping("send/{email}")
    public ResultBean send(@PathVariable String email, HttpSession session) {
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        try {
            CommonUtil.email(email, num);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.fail().msg("邮件发送失败");
        }
        session.setAttribute(email, num);

        return ResultBean.success().msg("邮件发送成功");
    }

    @PostMapping("find")
    public ResultBean find(@RequestBody String data, HttpSession session) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        JSONObject jsonObject = JSONObject.parseObject(data);
        String email = jsonObject.getString("email");
        int code = jsonObject.getInteger("code");
        if (session.getAttribute(email) == null) {
            return ResultBean.fail().msg("验证码不正确");
        } else {
            int session_code = (int) session.getAttribute(email);
            if (code == session_code) {
                String password = jsonObject.getString("password");
                String encode_password = bCryptPasswordEncoder.encode(password);
                boolean result = userService.updatePasswordByEmail(email, encode_password);
                if (result) {
                    return ResultBean.success().msg("密码更新成功");
                }
                return ResultBean.fail().msg("密码更新失败");
            }
        }
        return ResultBean.fail().msg("密码更新失败");
    }


    @PostMapping("suborder")
    public ResultBean suborder(@RequestBody String data) {
        System.out.println(data);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SelfUserDetail userDetail = (SelfUserDetail) authentication.getPrincipal();
        System.out.println(userDetail.getId());
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String cart = jsonObject.getString("cart");
            cart = cart.substring(0, cart.length() - 1);
            String[] arrItem = cart.split(",");
            List<Integer> listPid = new ArrayList<>();
            Map<Integer, Integer> map = new HashMap<>();
            for (String s : arrItem) {
                String[] strArr = s.split("-");
                listPid.add(Integer.valueOf(strArr[0]));
                map.put(Integer.valueOf(strArr[0]), Integer.valueOf(strArr[1]));
            }
            for(Integer key : map.keySet()){
                Integer value = map.get(key);
                System.out.println(key+"  "+value);
            }
            userService.payOrder(userDetail.getId(),Integer.parseInt(jsonObject.getString("addressId")), jsonObject.getString("content"), map);
        } catch (Exception e) {
            System.out.println(e);
            return ResultBean.fail().msg("数据解析异常");
        }
        return ResultBean.success().msg("订单提交成功");
    }

    @GetMapping("orderInfo/{sid}")
    public ResultBean orderInfo(@PathVariable String sid) {
        List<Map<String, Object>> info = userService.orderInfo(sid);
        return ResultBean.success().data(info).msg("获取订单信息成功");
    }

    @PostMapping("modify_password")
    public ResultBean modify(@RequestBody String data, HttpSession session) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SelfUserDetail userDetail = (SelfUserDetail) authentication.getPrincipal();
        JSONObject jsonObject = JSONObject.parseObject(data);
        User user = userService.selectByEmail(userDetail.getEmail());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (bCryptPasswordEncoder.matches(jsonObject.getString("old_password"),user.getPassword())) {
            boolean result = userService.updatePasswordByEmail(userDetail.getEmail(), bCryptPasswordEncoder.encode(jsonObject.getString("new_password")));
            if (result) return ResultBean.success().msg("密码更新成功");
            else return ResultBean.fail().msg("密码更新失败");
        } else return ResultBean.fail().msg("原密码错误");
    }

}
